<?php
namespace App\Http\Controllers\Front;

use App\Models\Banners;
use App\Models\BbsCategory;
use App\Models\BbsQuestion;
use App\Models\BbsQuestionThanks;
use App\Models\Ads;
use App\Models\BbsAnswer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use YuanChao\Editor\EndaEditor;
use App\Models\UserCollect;
use App\Models\BbsHots;
use Illuminate\Support\Facades\Log;
use App\Models\Employ;
use App\Models\Teaches;
use Illuminate\Database\Eloquent\Model;

class BbsController extends MasterController{

    private $nav;
	/**
 * Create a new controller instance.
 *
 * @return void
 */ 
    public function __construct()
    {
    //      $this->middleware('auth');
      parent::__construct();
      $this->nav = 4;
      $this->ads = Ads::with(['getPositionName'=>function($query){
          $query->where('alias', '侧面');
      }])->where(['app' => 'bbs'])->skip(0)->take(3)->get();

      //就业指南 热门文章
      $this->employ = Employ::where(array('is_recommond'=>1,'is_validate'=>1))->orderBy('updated_at','desc')->skip(0)->take(5)->get();

      //充电加油 热门课程
      $this->teaches = Teaches::where('is_validate','=',1)->orderBy('views_num','desc')->orderBy('attention_num','desc')->orderBy('updated_at','desc')->skip(0)->take(5)->get();

    }

	/**
    * 青苜社区
    */
    public function index(Request $req)
    {
        $pages = $req->input('pages',1);
        $skip = ($pages-1)*2;
        //首页推荐问题
        $hotquestion = BbsHots::with(['getQuestion'=>function($query){
            $query->where('deleted_at','=',NULL);
        }])->orderBy('sort','desc')->orderBy('created_at','DESC')->skip($skip)->take(2)->get();
        
        foreach ($hotquestion as &$hq)
        {
            $hq->categoryName = count($hq->getQuestion->category)>0?$hq->getQuestion->category->title:'';
            $hq->categoryId = count($hq->getQuestion->category)>0?$hq->getQuestion->category->id:'';
            $hq->username = getUserName($hq->getQuestion->publish_uid);
            $hq->title    = $hq->getQuestion->title;
            $hq->focus_count = $hq->getQuestion->focus_count; 
            $hq->answer_count = $hq->getQuestion->answer_count;
            $hq->intro = str_limit(strip_tags($hq->intro),270);
            $hq->created = $this->tranTime($hq->getQuestion->created_at);
        }

        if($req->ajax())
        {
            if(count($hotquestion)>0)
            {
                return $this->formatJson('success','获取数据成功',$hotquestion,'',$pages+1);
            }
            else 
            {
                return $this->formatJson('error','没有更多数据','','',$pages);
            }
        }
        else
        {
            //轮播banner图片
            $banner = Banners::where(array('app'=>'bbs'))->orderBy('sort','asc')->orderBy('created_at','desc')->skip(0)->take(4)->get();
            //热门板块
            $hotbbs = BbsCategory::where('is_hot','=',1)->where('parent_id','<>',0)->orderBy('sort','desc')->get();
            //社区热帖
            $hotpost = BbsQuestion::where('is_hot','=',1)->orderBy('view_count','desc')->orderBy('focus_count','desc')->orderBy('answer_users','desc')->skip(0)->take(6)->get();

            return view('front.bbs.index')->with('nav',$this->nav)->with('banners',$banner)->with('hotuestion',$hotquestion)
                    ->with('hotbbs',$hotbbs)->with('hotpost',$hotpost)->with('hotemploy',$this->employ)->with('hotteaches',$this->teaches)->with("pages",2);
        }
    }


    /**
     * 发帖页面显示
     */
    public function posting()
    {
        $this->middleware('auth');
        $cid = Input::get('cid',0);
        $qid = Input::get('qid',0);
        //一级分类
        $category = BbsCategory::where('parent_id','=',0)->orderBy('sort','desc')->get();
        //社区热帖
        $hotpost = BbsQuestion::where('is_hot','=',1)->orderBy('view_count','desc')->orderBy('focus_count','desc')->orderBy('answer_users','desc')->skip(0)->take(8)->get();
        if($cid){
            //当前子分类信息
            $subcategory = BbsCategory::find($cid);
            if(!empty($subcategory)){
                //当前父分类下所有子分类
                $pcategory = BbsCategory::where('parent_id','=',$subcategory->parent_id)->orderBy('sort','desc')->get();
            }else{
                $pcategory= array();
            }
            if($qid){
                $quedetails = BbsQuestion::find($qid); //帖子详情
                $quedetails->details = strip_tags(EndaEditor::MarkDecode($quedetails->detail));
                return view('front.bbs.posting')
                    ->with('nav',$this->nav)
                    ->with('category',$category)
                    ->with('hotpost',$hotpost)
                    ->with('subcategory',$subcategory)
                    ->with('pcategory',$pcategory)
                    ->with('quedetails',$quedetails);
            }else{
                return view('front.bbs.posting')
                    ->with('nav',$this->nav)
                    ->with('category',$category)
                    ->with('hotpost',$hotpost)
                    ->with('subcategory',$subcategory)
                    ->with('pcategory',$pcategory);
            }
        }else{
            return view('front.bbs.posting')
                ->with('nav',$this->nav)
                ->with('category',$category)
                ->with('hotpost',$hotpost);
        }
    }

    /**
     * 保存
     * @param \Illuminate\Support\Facades\Request $req
     */
    public function store(Request $req)
    {
        $this->validate($req, [
            'plate_first_id'          => 'required|integer',
            'title'         => 'required|max:255',
            'detail'        => 'required|min:50'
        ]);
        
        if(empty($this->user))
            return $this->formatJson('error','请先登录','','/');
        $userid = $this->user->id;
        $data = $req->only('plate_first_id','plate_child_id','title','detail','questionid');
        if(!empty($data['questionid']) && is_numeric($data['questionid']) && $data['questionid'] > 0)
        {
            $question = BbsQuestion::where(array('publish_uid'=>$userid,'id'=>$data['questionid']))->first();
            if(empty($question))
                return $this->formatJson('error','您的请求出错了！');
            if($data['plate_first_id'])
                $question->category_id = $data['plate_first_id'];
            if($data['plate_child_id'])
                $question->category_id = $data['plate_child_id'];
            $question->title = $data['title'];
            $question->detail = $data['detail'];
            $question->save();
        }else{
            $insertArr = array();
            if($data['plate_first_id'])
                $insertArr['category_id'] = $data['plate_first_id'];
            if($data['plate_child_id'])
                $insertArr['category_id'] = $data['plate_child_id'];
            if(empty($insertArr['category_id']))
                return $this->formatJson('error','板块不可为空！');
            $insertArr['title'] = $data['title'];
            $insertArr['detail'] = $data['detail'];
            $insertArr['publish_uid'] = $userid;
            $question = BbsQuestion::firstOrCreate($insertArr);
        }
        return $this->formatJson('success','发布成功！',$question,'/bbs/'.$question->id);
    }

	/**
	 * 社区详情页
	 * @return [type] [description]
	 */
      public function show($id)
    {
         $result = BbsQuestion::find($id);
         if(empty($result)) abort(404);
         $result->incrementAdd('view_count',1);
         $categoryName = BbsCategory::where('id','=',$result->category_id)->first();
         if(empty($categoryName)) abort(404);
         $BbsAnswerComment = BbsAnswer::with(['getAnswerComment'=>function ($query){
                $query->orderBy('created_at','desc');
            }])->where(array('question_id'=>$id))->orderBy('created_at','desc')->get();
         $question = BbsQuestion::orderBy('view_count','desc')->orderBy('answer_users','desc')->skip(0)->take(4)->get();
         $mianbaoxie = $this->mianbaoxie('bbs',0,0,0, $result->category_id, '青苜社区',$result->title,'');
         $result->detail = EndaEditor::MarkDecode($result->detail);
         if(!empty($this->user)){
             $ucollect = UserCollect::where(array('app'=>'bbs','app_id'=>$result->id,'user_id'=>$this->user->id))->first();
         }
         if(!empty($ucollect))
         {
             $result->is_collect = 1;
         }
         else
         {
             $result->is_collect = 0;
         }
         //热门板块
         $hotbbs = BbsCategory::where('is_hot','=',1)->where('parent_id','<>',0)->orderBy('sort','desc')->get();
         return view('front.bbs.details')
                ->with('categoryName',$categoryName)
                ->with('BbsAnswerComment',$BbsAnswerComment)
                ->with('nav',$this->nav)
                ->with('arr',$result)
                ->with('question',$question)
                ->with('ads_img',$this->ads)
                ->with('mianbaoxie',$mianbaoxie)
                ->with('hotbbs',$hotbbs)
                ->with('hotemploy',$this->employ)
                ->with('hotteaches',$this->teaches);
    }

 
    /**
     * 
     * @param Request $request
     * @return 点赞功能
     */
    public function praise(Request $request)
    {
        $qid = $request->input('qid');
        $username = getUserName($this->user->id);
        $appr = BbsQuestionThanks::where(array('question_id'=>$qid,'user_id'=>$this->user->id,'user_name'=>$username))->get();
        if(!empty($appr) && count($appr)>0)
        {
            return $this->formatJson('error','您已经点过赞了,请勿重复点赞！');
        }
        $bbsq = BbsQuestion::find($qid);
        if(empty($bbsq))
        {
            return $this->formatJson('error','点赞失败，未找到相关帖子！');
        }
        $bbst = new BbsQuestionThanks();
        $bbst->user_id = $this->user->id;
        $bbst->question_id = $qid;
        $bbst->user_name = $username;
        try {
            $bbst->save();
            if($bbsq)
            {
                $bbsq->incrementAdd('thanks_count',1);
            }
        }catch (\PDOException $e){
            Log::info(['社区点赞异常'=>$e->getMessage()]);
            return $this->formatJson('falses','数据异常！');
        }
        return $this->formatJson('success','点赞成功！');
    }

    /**
     * 青苜社区板块详情
     */
    public function board($id)
    {
       $result = BbsCategory::find($id);
       if(empty($result)) abort(404);
       $typeid = Input::get('type',0);
       $sort = Input::get('sort',0);
       $page = Input::get('page',0);
       $page_size = 15;
       $page_size_big = 50;
       $skip = $page * $page_size;
       $skipbig = $page * $page_size_big;;

       $query = BbsQuestion::where(array('category_id'=>$id));
        switch ($sort){
            case 1:  //发帖时间
                $query->orderBy('created_at','desc');
                break;
            case 2:  //回复/阅读
                $query->orderBy('answer_users','desc')->orderBy('view_count','desc');
                break;
            case 3:  //阅读数
                $query->orderBy('view_count','desc');
                break;
            case 4:  //最新回复
                $query->orderBy("updated_at",'desc');
                break;
            case 5:  //热度
                $query->orderBy('answer_users','desc')->orderBy('answer_count','desc')->orderBy('view_count','desc')->orderBy('focus_count','desc');
                break;
            default:
                $query->orderBy('id','desc');

        }
       if($typeid == 2){  //热门
           $question = $query->orderBy('updated_at','desc')->skip($skipbig)->take($page_size_big)->get();
       }else{
           $question = $query->orderBy('updated_at','desc')->skip($skip)->take($page_size)->get();
       }
        foreach ($question as &$ques)
        {
            $ques->username = getUserName($ques->publish_uid);
            $ques->userlogo = userlogo($ques->publish_uid,'small');
            $ques->titname = str_limit($ques->title,40);
            $ques->createdtime = $this->tranTime($ques->created_at);
        }
        if(\Illuminate\Support\Facades\Request::ajax())
        {
            if(count($question)>0)
            {
                $pages = $page+1;
                return Response::json(array('msg'=>'获取数据成功',
                                            'status'=>'success',
                                            'data'=>$question,
                                            'pages'=>$pages));
            }
            else
            {
                return Response::json(array('msg'=>'没有更多数据','status'=>'falses'));
            }
        }
        else
        {
            //推荐帖子
            $hotquestion = BbsQuestion::where(array('category_id'=>$id,'is_hot'=>1))->orderBy('id','desc')->get();
            foreach ($hotquestion as &$hques)
            {
                $hques->username = getUserName($hques->publish_uid);
                $hques->userlogo = userlogo($hques->publish_uid,'small');
                $hques->titname = str_limit($hques->title,40);
                $hques->createdtime = $this->tranTime($hques->created_at);
            }
            //社区热帖
            $hotpost = BbsQuestion::where('is_hot','=',1)->orderBy('view_count','desc')->orderBy('focus_count','desc')->orderBy('answer_users','desc')->skip(0)->take(6)->get();
            //检查一分钟内当前板块是否有新回复
            $newanswer = BbsAnswer::where('category_id','=',$id)->whereBetween('created_at', [date("Y-m-d H:i:s",time() - 60), date("Y-m-d H:i:s",time())])->get();

            return view('front.bbs.board')
                ->with('nav',$this->nav)
                ->with('categoryid',$id)
                ->with('now_type',$typeid)
                ->with('now_sort',$sort)
                ->with('hotquestion',$hotquestion)
                ->with('question',$question)
                ->with('result',$result)
                ->with('hotpost',$hotpost)
                ->with('newanswer',$newanswer)
                ->with("pages",1)->with('hotemploy',$this->employ)->with('hotteaches',$this->teaches);
        }

    }

    /**
     * 青苜社区板块新回复刷新
     */
    public function refresh()
    {
        $id = Input::get('id',0);
        //检查一分钟内当前板块是否有新回复
        $newanswer = BbsAnswer::where('category_id','=',$id)->whereBetween('created_at', [date("Y-m-d H:i:s",time() - 60), date("Y-m-d H:i:s",time())])->get();

        if(count($newanswer) > 0){
            $question = BbsQuestion::where(array('category_id'=>$id))
                      ->orderBy("updated_at",'desc')
                      ->skip(0)->take(15)->get();
            foreach ($question as &$ques)
            {
                $ques->username = getUserName($ques->publish_uid);
                $ques->userlogo = userlogo($ques->publish_uid,'small');
                $ques->titname = str_limit($ques->title,40);
                $ques->createdtime = date('Y-m-d',strtotime($ques->created_at));
            }
            return Response::json(array('msg'=>'获取数据成功',
                            'status'=>'success',
                            'data'=>$question));
        }else{
             return Response::json(array('msg'=>'暂无新回复主题',
                            'status'=>'falses'));
        }

    }

    /**
     * 帖子搜索
     */
    public function search($keyword)
    {
        $count = BbsQuestion::where('title','like','%'.$keyword.'%')->count();
        if(!$count || empty($count))
        {
            $list = BbsQuestion::with('cateuse')
                    ->select('bbs_question.*','u.name')
                    ->join('users as u','u.id','=','bbs_question.publish_uid')
                    ->where('u.name','like','%'.$keyword.'%')
                    ->orderby('is_hot','desc')
                    ->orderby('view_count','desc')
                    ->paginate(20);
            $count = BbsQuestion::with('cateuse')
                    ->join('users as u','u.id','=','bbs_question.publish_uid')
                    ->where('u.name','like','%'.$keyword.'%')->count();
        }
        else
        {
            $list = BbsQuestion::with('cateuse')
                    ->select('bbs_question.*','u.name')
                    ->join('users as u','u.id','=','bbs_question.publish_uid')
                    ->where('title','like','%'.$keyword.'%')
                    ->orderby('is_hot','desc')
                    ->orderby('view_count','desc')
                    ->paginate(20);
            $count = BbsQuestion::with('cateuse')
                    ->join('users as u','u.id','=','bbs_question.publish_uid')
                    ->where('title','like','%'.$keyword.'%')->count();
        }
        
        return view('front.bbs.search')->with('count',$count)->with('keyword',$keyword)->with('list',$list)->with('nav',$this->nav);
    }

    /**
     * ajax点击加载更多处理
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function moreBbs(Request $request)
    {
        $page = $request->input('page',0);
        $page_size = 5;
        $skip = $page * $page_size;
        $data = BbsQuestion::where('is_hot','=',1)->orderBy('id','asc')->skip($skip)->take($page_size)->get();
        foreach ($data as &$value) {
            $value['cate_title'] = $value->category->title;
            $value['cate_icon'] = $value->category->icon;
        }
        $pages = $page+1;
        return Response::json(array('msg'=>'获取成功','status'=>'success','data'=>$data,'pages'=>$pages));
    }
}
